package com.minelx.sequence.core;

import java.util.ArrayList;
import java.util.List;

public class OrMatcher<R, T> implements ReturnMatcher<R, T> {
	private final List<ReturnMatcher<? extends R, T>> children;

	private OrMatcher(List<ReturnMatcher<? extends R, T>> children) {
		this.children = children;
	}

	public void add(ReturnMatcher<? extends R, T> child) {
		children.add(child);
	}

	@Override
	public boolean isMatch(T clue) {
		return children.stream().anyMatch(child -> child.isMatch(clue));
	}

	@Override
	public R onMatched(T clue) {
		return children.stream()
				.filter(which -> which.isMatch(clue))
				.findFirst().orElseThrow(RuntimeException::new)
				.onMatched(clue);
	}

	public static <R, T> OrMatcher<R, T> create(List<ReturnMatcher<? extends R, T>> matchers) {
		return new OrMatcher<>(matchers);
	}

	public static <R, T> OrMatcher<R, T> empty() {
		return new OrMatcher<>(new ArrayList<>());
	}
}
